<?php
namespace ac\behaviors;

use Yii;
use yii\base\Behavior;

class Sort extends Behavior
{
	/*
    列表排序
    $model          模型对象
    $primaryKey     主键字段
    $sort           排序数据，主键ID数组 
    */
    public function setSortList($model, $sort)
    {
        // P($model->primaryKey()[0]);
        $origin = $sort;
        $sort = implode(',', $sort);
        $sql = 'select sort from '. $model::tableName() .' where find_in_set ('. $model->primaryKey()[0] .', :sort) order by sort desc limit 0, 1';
        //获取 传过来的数据中，在老排序的第一位数据 是当前数据中排序值最大的，
        //当前面没有数据的时候，此最大排序值就是起始值
        $currMaxSort = $model::findBySql($sql, [':sort' => $sort])->one();
        $sql = 'select sort from '. $model::tableName() .' where sort > (' . $sql . ') order by sort asc limit 0, 1';
        // echo $sql;
        $res = $model::findBySql($sql, [':sort' => $sort])->one();//获取老排序 紧挨着的前一个排序值
        if(is_null($res) or $res->sort == 0){//如果没有 或前一个排序值也0，则从1开始计算
            $sortNum = $currMaxSort->sort+1;
        }else{
            $sortNum = $res->sort;
        }
        // P($sortNum);
        $transaction = Yii::$app->db->beginTransaction();//事物处理
        try{
            foreach($origin as $k => $v){
                $sortNum--;
                // $AppCategory = new $model;
                $model->updateAll(['sort' => $sortNum], $model->primaryKey()[0] . ' = :id', [':id' => $v]);
            }
            // $backInfo = [0, '设置排序成功'];//返回信息
            $transaction->commit();
            return true;
        }catch(\Exception $exception){
            $transaction->rollback();
        };
    }

    /*
    tree类型列表排序
    $model          模型对象
    $sortId         被拖动对象ID
    $targetId       目标对象的ID
    $location       ‘before’目标对象的上方，'after'目标对象的下方
    */
    public function setSortTreeList($model, $sortId, $targetId, $location)
    {
        /*取出目标对象的sort值 为了取出需要排序的列表*/
        $target = $model::find()->select([$model->primaryKey()[0], 'sort'])
                                  ->where($model->primaryKey()[0] . ' = :id', [':id' => $targetId])
                                  ->asArray()->one();

        if($location == 'before'){//排到目标前面
            $sql = 'select '. $model->primaryKey()[0] .',sort from '. $model::tableName() .' where parentid = (select parentid from '. $model::tableName() .' where '. $model->primaryKey()[0] .'=:sortid) and sort>=:targetsortid order by sort asc';
        }else{//排到目标后面
            $sql = 'select '. $model->primaryKey()[0] .',sort from '. $model::tableName() .' where parentid = (select parentid from '. $model::tableName() .' where '. $model->primaryKey()[0] .'=:sortid) and sort>:targetsortid order by sort asc';
        }
        /*取出所有需要改动排序值的数据*/
        $sortList = $model::findBySql($sql,[':sortid'=>$sortId, ':targetsortid'=>$target['sort']])->asArray()->all();
        // P($sortList);
        $transaction = Yii::$app->db->beginTransaction();//事物处理
        $pass = true;
        try{
            if($sortList){
                //修改被排序的数据
                $model::updateAll(['sort' => $sortList[0]['sort']], $model->primaryKey()[0] . ' = :sortid', [':sortid' => $sortId]);
                $i = 0;
                /*修改 其他数据*/
                foreach($sortList as $k => $v){
                    if($v[$model->primaryKey()[0]] != $sortId){
                        $i++;
                        $model::updateAll(['sort' => ($sortList[0]['sort']+$i)], $model->primaryKey()[0] . ' = :id', [':id' => $v[$model->primaryKey()[0]]]);
                    }
                }
            }else{//排序到最后一个，就会出现没有数据，只需要把被排序的对象改成最后一个即可
                $model::updateAll(['sort' => ($target['sort']+1)], $model->primaryKey()[0] . ' = :sortid', [':sortid' => $sortId]);
            }

            if($pass){
                // $backInfo = [0, '菜单排序成功'];//返回信息
                $transaction->commit();
                return true;
            }
        }catch(\Exception $exception){
            $transaction->rollback();       
        };
    }

}
?>